package tools

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

// 发送 HTTP 请求
func SendHttpRequest(method, url string, headers map[string]string, body []byte, timeout time.Duration) ([]byte, error) {
	// 创建 HTTP 客户端
	client := &http.Client{
		Timeout: timeout, // 设置超时时间
	}

	// 创建请求
	req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
	if err != nil {
		return nil, fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应体失败: %v", err)
	}

	// 检查状态码
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("请求失败，状态码: %d, 响应: %s", resp.StatusCode, string(responseBody))
	}

	return responseBody, nil
}

func (t Command) Curl() {
	if len(os.Args) != 3 {
		fmt.Println("请求参数有误！请参考：yt curl http://127.0.0.1")
		return
	}
	// 示例：发送 GET 请求
	url := os.Args[2]
	headers := map[string]string{
		"Content-Type": "application/json",
	}

	response, err := SendHttpRequest(http.MethodGet, url, headers, nil, 10*time.Second)
	if err != nil {
		fmt.Println("GET 请求失败:", err)
		return
	}
	fmt.Println("GET 请求成功，响应:", string(response))

	// 示例：发送 POST 请求
	/*postUrl := "https://jsonplaceholder.typicode.com/posts"
	postBody := []byte(`{
		"title": "foo",
		"body": "bar",
		"userId": 1
	}`)

	response, err = SendHttpRequest(http.MethodPost, postUrl, headers, postBody, 10*time.Second)
	if err != nil {
		fmt.Println("POST 请求失败:", err)
		return
	}
	fmt.Println("POST 请求成功，响应:", string(response))*/
}
